﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MebAppMarketplace.Helpers
{
    public class HashHelper
    {
        public static String ComputeFileMD5(String fileName)
        {
            String hashMD5 = String.Empty;
            //检查文件是否存在，如果文件存在则进行计算，否则返回空值
            if (System.IO.File.Exists(fileName))
            {
                using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //计算文件的MD5值
                    using (System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create())
                    {
                        Byte[] buffer = calculator.ComputeHash(fs);
                        //将字节数组转换成十六进制的字符串形式
                        StringBuilder stringBuilder = new StringBuilder();
                        for (int i = 0; i < buffer.Length; i++)
                        {
                            stringBuilder.Append(buffer[i].ToString("x2"));
                        }
                        hashMD5 = stringBuilder.ToString();
                    }
                }//关闭文件流
            }//结束计算
            return hashMD5;
        }
        public static String ComputeStreamMD5(Stream stream)
        {
            String hashMD5 = String.Empty;
            //计算文件的MD5值
            using (System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create())
            {
                Byte[] buffer = calculator.ComputeHash(stream);
                //将字节数组转换成十六进制的字符串形式
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < buffer.Length; i++)
                {
                    stringBuilder.Append(buffer[i].ToString("x2"));
                }
                hashMD5 = stringBuilder.ToString();
            }
            return hashMD5;
        }
    }
}
